package com.freeman.cement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.freeman.cement.entity.AutoAssignmentConfig;
import com.freeman.cement.entity.ResponseResult;
import com.freeman.cement.entity.Staff;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.mapper.AutoAssignmentConfigDao;
import com.freeman.cement.mapper.StaffDao;
import com.freeman.cement.service.AutoAssignmentService;
import com.freeman.cement.util.PageHelperForListUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 自动转发规则配置Service
 */
@Service
public class AutoAssignmentServiceImpl implements AutoAssignmentService {

    @Resource
    private AutoAssignmentConfigDao autoAssignmentConfigDao;

    @Resource
    private StaffDao staffDao;

    /**
     * 根据事件类型码和摄像头编码查找自动转发规则
     * @param eventType
     * @param cameraIndexCode
     * @return
     */
    public AutoAssignmentConfig getAssignment(String eventType, String cameraIndexCode) {
        AutoAssignmentConfig config = null;
        QueryWrapper<AutoAssignmentConfig> qw = new QueryWrapper<>();
        qw.eq("eventType", eventType)
                .eq("cameraIndexCode", cameraIndexCode)
                .eq("isEnabled", true);
        List<AutoAssignmentConfig> list = autoAssignmentConfigDao.selectList(qw);
        if (list != null && list.size() > 0) {
            config = list.get(0);
            if (config != null && StringUtils.isNotBlank(config.getUserIds())) {
                config.setUsers(selectUsers(config.getUserIds()));
                //对于一个摄像头id和一个事件类型，只能唯一匹配一组通知用户
                System.out.println("匹配到自动转发规则，事件类型：" + config.getEventType() + "，摄像头标识：" + config.getCameraIndexCode() + "，是否启用：" + config.getIsEnabled() + "，转发给用户：" + config.getUserIds());
            }
        }
        return config;
    }

    private List<Staff> selectUsers(String userStr){
        final String[] users = StringUtils.split(userStr, ",");
        if (users.length > 0) {
            List<Staff> staffList = new ArrayList<>();
            for (final String usr : users) {
                if (NumberUtils.isParsable(usr)) {
                    Staff staff = staffDao.selectById(NumberUtils.toInt(usr));
                    if (staff != null) {
                        staffList.add(staff);
                    }
                }
            }
            return staffList;
        }
        return null;
    }

    private List<AutoAssignmentConfig> selectAssignment(String cameraName, String eventTypeName, Boolean isEnabled, Boolean isSmsEnabled){
        List<AutoAssignmentConfig> assignmentConfigs = autoAssignmentConfigDao.selectAssignmentFuzzy(cameraName, eventTypeName, isEnabled, isSmsEnabled);
        //添加用户集合
        if (assignmentConfigs != null && assignmentConfigs.size() > 0) {
            for (AutoAssignmentConfig assignment : assignmentConfigs) {
                if (StringUtils.isNotBlank(assignment.getUserIds())) {
                    assignment.setUsers(selectUsers(assignment.getUserIds()));
                }
            }
        }
        return assignmentConfigs;
    }

    /**
     * 模糊查询自动转发规则
     *
     * @param cameraName    摄像头名称模糊
     * @param eventTypeName 事件类型名称模糊
     * @param recvUserName  接收人名称模糊
     * @param isEnabled     是否启用规则
     * @param isSmsEnabled  是否启用短信转发
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public ResponseResult selectAssignmentFuzzy(String cameraName, String eventTypeName, String recvUserName, Boolean isEnabled, Boolean isSmsEnabled, int pageNo, int pageSize) {
        if (pageNo < 1 || pageSize > 1000) {
            throw new AppException(AppExceptionCodeMsg.PAGE_NO_OR_SIZE_WRONG);
        }
        if (StringUtils.isBlank(recvUserName)) {
            //使用数据库分页
            PageHelper.startPage(pageNo, pageSize, true);
            List<AutoAssignmentConfig> assignmentConfigs = selectAssignment(cameraName, eventTypeName, isEnabled, isSmsEnabled);
            PageInfo<AutoAssignmentConfig> pageInfo = new PageInfo<AutoAssignmentConfig>(assignmentConfigs);
            return ResponseResult.success(pageInfo);
        } else {
            List<AutoAssignmentConfig> assignmentConfigs = selectAssignment(cameraName, eventTypeName, isEnabled, isSmsEnabled);
            Set<AutoAssignmentConfig> set = new HashSet<>();
            assignmentConfigs.forEach(s -> {
                s.getUsers().forEach(u -> {
                    if (u.getRealname().contains(recvUserName)) {
                        set.add(s);
                    }
                });
            });
            List<AutoAssignmentConfig> list = set.stream().collect(Collectors.toList());
            //使用list分页
            return ResponseResult.success(PageHelperForListUtil.getPageInfo(list, pageNo, pageSize));
        }
    }

    /**
     * 新增自动转发规则
     *
     * @param assignment
     * @return
     */
    @Override
    public ResponseResult addAssignment(AutoAssignmentConfig assignment) {
        if (assignment != null && StringUtils.isNotBlank(assignment.getUserIds()) && StringUtils.isNotBlank(assignment.getCameraIndexCode()) && StringUtils.isNotBlank(assignment.getEventType())) {
            //检查人员id集合是否正确
            List<String> list = new ArrayList<>();
            final String[] ids = StringUtils.split(assignment.getUserIds(), ",");
            for (String idstr : ids) {
                if (NumberUtils.isParsable(idstr)) list.add(idstr);
            }
            if (list.size() > 0) {
                assignment.setUserIds(StringUtils.join(list, ","));
            } else {
                throw new AppException(10500, "未选择接收人");
            }
            //查询是否有摄像头标识和事件类型码都存在自动转发规则
            QueryWrapper<AutoAssignmentConfig> qw = new QueryWrapper<>();
            qw.eq("cameraIndexCode", assignment.getCameraIndexCode());
            qw.eq("eventType", assignment.getEventType());
            Long count = autoAssignmentConfigDao.selectCount(qw);
            if (count > 0) {
                throw new AppException(10500, "已存在此摄像头和此事件类型的转发规则");
            } else {
                if (assignment.getIsEnabled() == null)
                    assignment.setIsEnabled(true);
                int rslt = autoAssignmentConfigDao.insert(assignment);
                if (rslt > 0) {
                    return ResponseResult.successMsg("新增成功");
                } else {
                    throw new AppException(AppExceptionCodeMsg.ADD_AUTO_ASSIGNMENT_ERROR);
                }
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
    }

    @Override
    public ResponseResult selectAssignmentById(int id) {
        if (id > 0) {
            AutoAssignmentConfig assignmentConfig = autoAssignmentConfigDao.selectAssignmentById(id);
            if (assignmentConfig != null) {
                if (StringUtils.isNotBlank(assignmentConfig.getUserIds())) {
                    assignmentConfig.setUsers(selectUsers(assignmentConfig.getUserIds()));
                }
                return ResponseResult.success(assignmentConfig);
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

    @Override
    public ResponseResult deleteAssignment(int id) {
        if (id > 0) {
            AutoAssignmentConfig assignmentConfig = autoAssignmentConfigDao.selectById(id);
            if (assignmentConfig != null) {
                int rslt = autoAssignmentConfigDao.deleteById(id);
                if (rslt > 0) {
                    return ResponseResult.successMsg("删除成功");
                } else {
                    throw new AppException(AppExceptionCodeMsg.DELETE_AUTO_ASSIGNMENT_ERROR);
                }
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

    @Override
    public ResponseResult updateAssignment(int id, String userIds, Boolean isEnabled, Boolean isSmsEnabled, String remark) {
        if (id > 0) {
            AutoAssignmentConfig old = autoAssignmentConfigDao.selectById(id);
            if (old != null) {
                boolean flag = false;
                AutoAssignmentConfig assignmentConfig = new AutoAssignmentConfig();
                assignmentConfig.setId(id);
                //用户id集合字符串
                if (StringUtils.isNotBlank(userIds)) {
                    List<String> list = new ArrayList<>();
                    String[] strings = StringUtils.split(userIds, ",");
                    for (String str : strings) {
                        if (NumberUtils.isParsable(str)) list.add(str);
                    }
                    String uidstr = StringUtils.join(list, ",");
                    if (StringUtils.isNotBlank(uidstr)) {
                        assignmentConfig.setUserIds(uidstr);
                        flag = true;
                    }
                }
                //备注
                if (StringUtils.isNotBlank(remark)) {
                    assignmentConfig.setRemark(remark);
                    flag = true;
                }
                //规则启用
                if (isEnabled != null) {
                    assignmentConfig.setIsEnabled(isEnabled);
                    flag = true;
                }
                //短信启用
                if (isSmsEnabled != null) {
                    assignmentConfig.setIsSmsEnabled(isSmsEnabled);
                    flag = true;
                }
                if (flag) {
                    int rslt = autoAssignmentConfigDao.updateById(assignmentConfig);
                    if (rslt > 0) {
                        return ResponseResult.successMsg("修改成功");
                    } else {
                        throw new AppException(AppExceptionCodeMsg.UPDATE_AUTO_ASSIGNMENT_ERROR);
                    }
                } else {
                    throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
                }
            } else {
                throw new AppException(AppExceptionCodeMsg.ID_NOT_EXISTS);
            }
        } else {
            throw new AppException(AppExceptionCodeMsg.ID_IS_NULL);
        }
    }

}
